package com.alan.netty.nio.channels;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author weiBin
 * @date 2018/11/7
 */
public class ServerSocketChannelAccess {
    static int port = 8081;
    private static final String MSG = "hello, I must be going \n";

    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ServerSocket serverSocket = ssc.socket();
        // Listen on port 8081
        serverSocket.bind(new InetSocketAddress(port));
        ssc.configureBlocking(false);
        System.out.println("服务器端口8081启动,等待客户端连接:");
        ByteBuffer buffer = ByteBuffer.wrap(MSG.getBytes());
        while (true) {
            System.out.println("wait for connection ……");
            SocketChannel sc = ssc.accept();

            if (sc == null) {
                // no connections, snooze a while ...
                Thread.sleep(2000);
            } else {
                System.out.println("Incoming connection from " + sc.socket().getRemoteSocketAddress());
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                sc.read(readBuffer);
                readBuffer.rewind();
                out(readBuffer);
                buffer.rewind();
                //write msg to client
                sc.write(buffer);
                sc.close();
                //ssc.close();
            }
        }
    }

    private static void out(ByteBuffer buffer) {
        StringBuffer sb = new StringBuffer();
        while (buffer.hasRemaining()) {
            char c = (char) buffer.get();
            sb.append(new String(new char[]{c}));
        }
        System.out.println(sb.toString());
    }
}
